package com.czp.infosharingplatformapp.service.impl;

import com.czp.infosharingplatformapp.dto.CategoryResponse;
import com.czp.infosharingplatformapp.dto.ResourceResponse;
import com.czp.infosharingplatformapp.model.Category;
import com.czp.infosharingplatformapp.model.Resource;
import com.czp.infosharingplatformapp.repository.CategoryRepository;
import com.czp.infosharingplatformapp.repository.ResourceRepository;
import com.czp.infosharingplatformapp.repository.UserRepository;
import com.czp.infosharingplatformapp.service.CategoryService;
import com.czp.infosharingplatformapp.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceRepository resourceRepository;

    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CategoryService categoryService;

    @Value("${file.upload.dir}")
    private String uploadDir;

    @Override
    public Resource saveResource(MultipartFile file, String description, Long categoryId, Long uploaderId) throws IOException {
        // 准备存储目录
        File uploadDirFile = new File(uploadDir);
        if (!uploadDirFile.exists()) {
            uploadDirFile.mkdirs();
        }

        String uniqueFileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
        String filePath = uploadDir + uniqueFileName;
        file.transferTo(new File(filePath));

        // 查询分类和用户
        Category category = categoryRepository.findById(categoryId)
                .orElseThrow(() -> new RuntimeException("分类不存在"));
        var uploader = userRepository.findById(uploaderId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 保存文件信息到数据库
        Resource resource = new Resource();
        resource.setFileName(file.getOriginalFilename());
        resource.setFilePath(filePath);
        resource.setDescription(description);
        resource.setCategory(category);
        resource.setUploader(uploader);
        resource.setUploadedAt(LocalDateTime.now());

        return resourceRepository.save(resource);
    }

    @Override
    public Resource findById(Long id) {
        return resourceRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("文件资源不存在！"));
    }

    @Override
    public List<Resource> searchByFileName(String keyword) {
        return resourceRepository.findByFileNameContaining(keyword);
    }

    @Override
    public List<Resource> filterByCategory(Long categoryId) {
        Category category = categoryRepository.findById(categoryId)
                .orElseThrow(() -> new RuntimeException("分类不存在！"));
        return resourceRepository.findByCategory(category);
    }

    @Override
    public void deleteResource(Long resourceId) {
        if (!resourceRepository.existsById(resourceId)) {
            throw new RuntimeException("资源不存在");
        }
        resourceRepository.deleteById(resourceId); // 删除资源
    }

    @Override
    public List<Resource> getAllResources() {
        return resourceRepository.findAll(); // 实现获取所有资源的逻辑
    }

    public ResourceResponse convertToResourceResponse(Resource resource) {
        ResourceResponse response = new ResourceResponse();
        response.setId(resource.getId());
        response.setFileName(resource.getFileName());
        response.setFilePath(resource.getFilePath());
        response.setUploadedAt(resource.getUploadedAt());
        response.setDescription(resource.getDescription());
        response.setUploader(resource.getUploader());

        Category category = resource.getCategory();
        if (category != null) {
            CategoryResponse categoryResponse = categoryService.convertToCategoryResponse(category);
            response.setCategory(categoryResponse);
        }

        return response;
    }
}